package listeners;

import android.app.Activity;
import android.app.AlertDialog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;

import com.unipv14.androidgallery.CurrentImageActivity;
import com.unipv14.androidgallery.IListsRefresher;
import com.unipv14.androidgallery.ImageShower;

import fileManagers.FileUtilities;
import fileManagers.FilterImage;

/**
 * 
 * Generalizzazione dei listeners sulle liste
 * 
 */
public class ItemListener implements OnItemClickListener,
		OnItemLongClickListener {

	private IListsRefresher listRefresher;
	private Activity mainActivity;
	private String selectedFile;
	private IListener listener;

	public ItemListener(IListener listener,IListsRefresher listRefresher,
			Activity mainActivity) {
		this.listener = listener;
		this.listRefresher=listRefresher;
		this.mainActivity=mainActivity;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {

		selectedFile = (String) arg0.getItemAtPosition(position);
		if (new FilterImage().checkFilter(selectedFile,
				listener.getFolder(selectedFile))) {
			selectedFile = FileUtilities.nameToPath(
					listener.getFolder(selectedFile), selectedFile);
			ImageShower.showImage(listener.getListPath(), mainActivity,
					selectedFile,CurrentImageActivity.class);
		} else {
			listener.goToSubDirectory(selectedFile);
			listRefresher.refreshList();
		}
		listener.setSelectedFile(selectedFile);
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
			int position, long id) {

		selectedFile = (String) arg0.getItemAtPosition(position);
		listener.setSelectedFile(selectedFile);
		if (listener.getMenuOptions(selectedFile).length == 0) {
			return true;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity);
		builder.setAdapter(
				new ArrayAdapter<>(mainActivity,
						android.R.layout.simple_list_item_1, listener
								.getMenuOptions(selectedFile)), listener);
		AlertDialog dialog = builder.create();
		listener.setSelectedFile(selectedFile);
		dialog.show();
		return true;
	}

}
